package org.spring.springcloud.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;


/**
 * Created by zhaomj on 2017/4/27.
 */
@Configuration
@EnableAutoConfiguration
public class RedisConfiguration {

    //(一)第一步：配置连接池,
    /*
    @ConfigurationProperties和@Bean和在一起使用
    举个例子，我们需要用@Bean配置一个Config对象，Config对象有a，b，c成员变量需要配置，
    那么我们只要在yml或properties中定义了a=1,b=2,c=3，然后通过@ConfigurationProperties就能把值注入进Config对象中
    */
    @Bean
    @ConfigurationProperties(prefix="spring.redis.pool")
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();

        System.out.println("config.toString="+config.toString()+" max-idle="+config.getMaxIdle()+"MinIdle="+config.getMinIdle());
        return config;
    }


    //第二步：配置工厂类JedisConnectionFactory，并设置ip，端口和连接池
    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisConnectionFactory getConnectionFactory(){
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setUsePool(true);
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        System.out.println("Timeout="+factory.getTimeout()+"port="+factory.getPort()+"host="+factory.getHostName());
        return factory;
    }

    //第三步：创建StringRedisTemplate操作类,程序中可直接使用该类进行增加，删除等操作
    @Bean
    public RedisTemplate<?, ?> getRedisTemplate(){
        RedisTemplate<?,?> template = new StringRedisTemplate(getConnectionFactory());
        return template;
    }

    @Bean
    public RedisTemplate redisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(getConnectionFactory());
        return redisTemplate;
    }
//
//    @Bean
//    public StringRedisTemplate stringRedisTemplate() {
//        StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
//        return template;
//    }
}
